#include<iostream>
#include<fcntl.h>
#include<unistd.h>
#include<cstring>

#define OPT_ONE 1
#define OPT_TWO 2
#define OPT_THREE 4
#define OPT_FOUR 8

void Func(int input)
{
    if(input & OPT_ONE)
    {
        std::cout << OPT_ONE << std::endl;
    }
    if (input & OPT_TWO)
    {
        std::cout << OPT_TWO << std::endl;
    }
    if (input & OPT_THREE)
    {
        std::cout << OPT_THREE << std::endl;
    }
    if ( input & OPT_FOUR)
    {
        std::cout << OPT_THREE << std::endl;
    }
    else
    {

    }
}

int main()
{
    //int fd = open("file.txt" , O_CREAT | O_RDONLY , 0666);

    //int fd = open("file.txt" , O_CREAT | O_WRONLY | O_APPEND , 0666); //fcntl.h
    //int fd = open("file.txt" , O_CREAT | O_WRONLY | O_TRUNC , 0666); //fcntl.h

    //close(0);


    //write content to file
    // int fd = open("file.txt" , O_CREAT | O_WRONLY, 0666); //fcntl.h
    // std::cout << "fd : " << fd << std::endl;
    // for(int i = 0 ; i< 5; i++)
    // {
    //     const char* buffer = "hello huangan\n";
    //     //const char* buffer = "your majesty\n";
    //     write(fd , buffer , strlen(buffer));   //unistd.h  
    // }       


    //read content from file
    // int fd = open("file.txt" , O_RDONLY);
    // char* buffer;
    // read(fd , buffer , 1024);

    // std::cout << buffer;


    // 基础的重定向
    // const char* str = "hahahahaha\n";
    // close(1);
    // int fd = open("file.txt" , O_CREAT | O_WRONLY | O_TRUNC , 0666);
    // std::cout << "fd : " << fd << std::endl;
    // write(fd,str,strlen(str));

    //使用dup2的重定向
    const char* str = "hahahahaha\n";
    int fd = open("file.txt" , O_CREAT | O_WRONLY | O_TRUNC , 0666);
    dup2(fd,1);
    //dup2(1,fd);
    printf("fd : %d\n",fd);
    write(fd,str,strlen(str)); //此时file.txt由于O_TRUNC被清空,但是str的内容输入到了屏幕上
   close(fd);


    //对比write 与 printf
    // int fd1 = open("write.txt" , O_CREAT | O_TRUNC | O_WRONLY , 0666);
    // const char* str = "Those are the contend burried deeply in my mind";
    // write(fd1,str,strlen(str));
    // close(fd1);

    // int fd2 = open("printf.txt" , O_CREAT | O_TRUNC | O_WRONLY , 0666);
    // const char* str2 = "Those are the contend burried deeply in my mind";
    // dup2(1,fd2);
    // printf("%s",str2);

   //测试位掩码
//    Func(OPT_FOUR | OPT_TWO);
//    Func(OPT_FOUR);
//    Func(OPT_TWO);
//    Func(OPT_ONE);
    return 0;
}
